<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <div slot="header" class="clearfix">
          <span>试题录入</span>
        </div>
        <el-form
          ref="ruleForm"
          :model="form"
          :rules="rules"
          label-width="120px"
          size="medium"
        >
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              v-model="form.subjectID"
              placeholder="请选择"
              style="width: 400px"
              @change="subjectChange"
            >
              <el-option
                v-for="item in subject"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录：" prop="catalogID">
            <el-select
              v-model="form.catalogID"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="item in catalog"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              v-model="form.enterpriseID"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="item in enterprise"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" prop="city">
            <el-select
              v-model="form.province"
              placeholder="请选择"
              style="width: 200px"
              @change="getCitys"
            >
              <el-option
                v-for="item in provinceData"
                :key="item.index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select
              v-model="form.city"
              placeholder="请选择"
              style="width: 200px"
            >
              <el-option
                v-for="item in cityData"
                :key="item.index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向：" prop="city">
            <el-select
              v-model="form.direction"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                v-for="item in directions"
                :key="item.index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group
              v-model="form.questionType"
              @change="questionTypeChange"
            >
              <el-radio :label="'1'">单选</el-radio>
              <el-radio :label="'2'">多选</el-radio>
              <el-radio :label="'3'">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="form.difficulty">
              <el-radio :label="'1'">简单</el-radio>
              <el-radio :label="'2'">一般</el-radio>
              <el-radio :label="'3'">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 富文本框 -->
          <el-form-item label="题干：" prop="question">
            <quill-editor
              ref="myLQuillEditor"
              v-model="form.question"
              :options="editorOption"
              class="editor"
            />
          </el-form-item>
          <el-form-item label="选项：" v-show="optionDialog">
            <div
              class="option-item"
              v-for="(item, index) in form.options"
              :key="index"
            >
              <el-radio
                class="el-radio-s"
                v-if="radioDialog"
                v-model="radioCheck"
                :label="index"
                >{{ String.fromCharCode(64 + index + 1) }}：</el-radio
              >

              <el-checkbox
                v-else
                v-model="item.isRight"
                :true-label="+1"
                :false-label="+0"
                >{{ String.fromCharCode(64 + index + 1) }}：</el-checkbox
              >
              <el-input
                v-model="item.code"
                autosize
                clearable
                style="width: 240px;"
              ></el-input>
              <el-upload
                class="avatar-uploader"
                :limit="1"
                action="http://geek.itheima.net/v1_0/upload"
                :headers="{
                  Authorization: 'Bearer c21fac04-blef-49e9-aeac-led92b26aec9'
                }"
                name="image"
                :on-success="handleAvatarSuccess"
                :before-remove="handleAvatarRemove"
                accept="image/png,image/gif,image/jpeg"
                :before-upload="beforeAvatarUpload"
                style="margin-left: 4px;"
              >
                <img
                  v-if="item.img"
                  :src="item.img"
                  class="avatar"
                  style="pointer-events: all"
                />
                <i v-else class="upload-text" @click="uploadIndex(index)"
                  >上传图片</i
                >
                <!-- <i class="el-icon-circle-close"></i> -->
              </el-upload>
            </div>
            <el-row class="question-change">
              <el-button
                type="danger"
                :disabled="plus"
                @click="optionNumChange('1')"
                >增加</el-button
              >
              <el-button
                type="warning"
                :disabled="less"
                @click="optionNumChange('0')"
                >删除</el-button
              >
            </el-row>
          </el-form-item>
          <el-form-item label="解析视频">
            <el-input v-model="form.videoURL" style="width: 400px"></el-input>
          </el-form-item>
          <!-- 富文本框 -->
          <el-form-item label="答案解析：" prop="answer">
            <quill-editor
              ref="myLQuillEditor"
              v-model="form.answer"
              :options="editorOption"
              class="editor"
            />
          </el-form-item>
          <el-form-item label="题目备注：">
            <el-input
              type="textarea"
              :rows="4"
              v-model="form.remarks"
              autocomplete="off"
              style="width: 400px;"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="试题标签：">
            <el-select
              v-model="form.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择试题标签"
              style="width: 400px"
            >
              <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item[1].tagName"
                :value="item[1].tagName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="form-button">
            <el-button v-if="submitButton" type="primary" @click="onSubmitAdd"
              >提交</el-button
            >
            <el-button v-else type="success" @click="onSubmitUpdate"
              >提交修改</el-button
            >
            <el-button v-show="!submitButton" @click="btnCancel"
              >取消</el-button
            >
            <el-button class="form-reset" @click="formReset">清空</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script>
// 引入样式和quillEditor
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
// 引入api
import { simple as simpleSubjects } from "../../api/hmmm/subjects";
import { simple as simpleDirectorys } from "../../api/hmmm/directorys";
import { list as companysList } from "../../api/hmmm/companys";
import { list as getTags } from "../../api/hmmm/tags";
import { add, update, detail } from "../../api/hmmm/questions";
// 引入城市
import { provinces, citys } from "../../api/hmmm/citys";
// 引入枚举
import { direction as directionList } from "../../api/hmmm/constants";
/**
 * 富文本框模块
 */
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  ["blockquote"], // 引用
  ["clean"], // 清除文本格式
  ["code-block", "image", "link"] // 代码，图片，链接
];
export default {
  name: "questions-new",
  components: {
    quillEditor
  },
  props: {
    value: {
      type: [Number, Object, Array, String],
      default: ""
    }
  },
  data() {
    return {
      id: this.$route.query.id,
      // id: 23,
      // 富文本框设置
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        theme: "snow",
        placeholder: ""
      },
      // 表单绑定数据
      form: {
        subjectID: "", // 学科
        catalogID: "", // 目录
        enterpriseID: "", // 企业
        province: "", // 地区
        city: "",
        direction: "", // 方向
        questionType: "", //问题类型
        difficulty: "", //问题难度
        question: "", //题干
        options: [
          // 选项
          { id: "", code: "", title: "", img: "", isRight: "" }, // 代码，标题，图片链接，是否正确
          { id: "", code: "", title: "", img: "", isRight: "" },
          { id: "", code: "", title: "", img: "", isRight: "" },
          { id: "", code: "", title: "", img: "", isRight: "" }
        ],
        videoURL: "", // 视频链接
        answer: "", // 答案
        remarks: "", // 备注
        tags: [] // 标签
      },
      // 空表单
      originalForm: {
        subjectID: "", // 学科
        catalogID: "", // 目录
        enterpriseID: "", // 企业
        province: "", // 地区
        city: "",
        direction: "", // 方向
        questionType: "", //问题类型
        difficulty: "", //问题难度
        question: "", //题干
        options: [
          // 选项
          { id: "", code: "", title: "", img: "", isRight: "" }, // 代码，标题，图片链接，是否正确
          { id: "", code: "", title: "", img: "", isRight: "" },
          { id: "", code: "", title: "", img: "", isRight: "" },
          { id: "", code: "", title: "", img: "", isRight: "" }
        ],
        videoURL: "", // 视频链接
        answer: "", // 答案
        remarks: "", // 备注
        tags: [] // 标签
      },
      // 表单数据
      subject: "", // 学科列表
      catalog: "", // 目录列表
      enterprise: "", // 企业列表
      provinceData: "", // 城市
      directions: "", // 方向
      cityData: "", // 地区
      radioDialog: true, // 单选/多选
      optionDialog: true, // 选项显示隐藏
      radioCheck: null, // 单选选中
      plus: true,
      less: true,
      tags: [],
      rules: {
        subjectID: [{ required: true, message: "请选择学科", trigger: "blur" }],
        catalogID: [{ required: true, message: "请选择目录", trigger: "blur" }],
        enterpriseID: [
          { required: true, message: "请选择企业", trigger: "blur" }
        ],
        city: [{ required: true, message: "请选择地区", trigger: "blur" }],
        questionType: [
          { required: true, message: "请选择题型", trigger: "blur" }
        ],
        difficulty: [
          { required: true, message: "请选择难度", trigger: "blur" }
        ],
        direction: [{ required: true, message: "请选择方向", trigger: "blur" }],
        question: [{ required: true, message: "请输入题干", trigger: "blur" }],
        answer: [{ required: true, message: "请输入答案", trigger: "blur" }]
      },
      titleText: "",
      submitButton: true, // 提交按钮样式
      pics: [],
      picIndex: ""
    };
  },
  computed: {},
  watch: {
    /**
     * 正确答案isRight
     */
    radioCheck() {
      if (this.form.questionType == 1) {
        this.checkReset(); // 先清空别的
        this.form.options[this.radioCheck].isRight = 1; // 选中相应isRight赋1
      }
    }
  },
  created() {
    this.getDetail();
    this.simpleSubjects();
    this.companysList();
    this.region();
    this.checkReset();
    this.getDirection();
    this.submitTextToggle();
  },
  mounted() {},
  beforeDestroy() {},
  methods: {
    /**
     * 获取简单学科列表
     */
    async simpleSubjects() {
      const { data } = await simpleSubjects();
      this.subject = data;
    },
    /**
     * 学科改变
     */
    async subjectChange(value) {
      this.catalog = ""; // 清空目录
      this.form.catalogID = "";
      const depts = await simpleDirectorys({
        subjectID: value,
        pagesize: 10000
      });
      this.catalog = depts.data;
      this.tags = []; // 清空标签
      this.form.tags = [];
      const {
        data: { items }
      } = await getTags({ subjectID: value, pagesize: 10000 });
      this.tags = Object.entries(items);
    },
    /**
     * 获取企业列表
     */
    async companysList() {
      const {
        data: { items }
      } = await companysList({ pagesize: 1000 });
      this.enterprise = items;
    },
    /**
     * 注入方向
     */
    getDirection() {
      this.directions = directionList;
    },
    /**
     * 注入城市数据
     */
    region() {
      this.provinceData = provinces();
    },
    /**
     * 获取对应地区
     */
    getCitys() {
      this.cityData = "";
      this.form.city = "";
      this.cityData = citys(this.form.province);
    },
    /**
     * 题型改变
     */
    questionTypeChange(value) {
      if (value == "1") {
        // 单选时
        this.radioDialog = true; // 切换单选
        this.optionDialog = true; // 显示选项
        this.radioCheck = null; // 清除选项
        this.checkReset(); // 清除isRight
        this.plus = true; // 禁用增加按钮
        this.less = true; // 禁用减少按钮
        this.form.options.splice(4); // 恢复表单options为4组
      } else if (value == "2") {
        // 多选时
        this.radioDialog = false; // 切换多选
        this.optionDialog = true; // 显示选项
        this.radioCheck = null; // 清除选项
        this.plus = false; // 启用增加按钮
      } else {
        // 简答
        this.optionDialog = false;
      }
    },
    /**
     * 选项增减
     */
    optionNumChange(value) {
      if (value == 1) {
        this.form.options.push({
          id: "",
          code: "",
          title: "",
          img: "",
          isRight: ""
        });
        this.plus = this.form.options.length == 7 ? true : false; // 长度为7时，禁用增加按钮
        this.less = false; // 点击增加后，直接启用减少按钮
      } else {
        this.form.options.pop();
        this.plus = false; // 点击减少后，直接启用增加按钮
        this.less = this.form.options.length == 4 ? true : false; // 当长度为4的时候，禁用减少按钮
      }
    },
    /**
     * 重置选项isRight
     */
    checkReset() {
      this.form.options.forEach(element => {
        // 所有isRight赋0
        element.isRight = 0;
      });
    },
    /**
     * 标题和提交按钮判断
     */
    submitTextToggle() {
      if (this.id) {
        // 有id显示修改
        this.titleText = "试题修改";
        this.submitButton = false;
      } else {
        // 无id显示录入
        this.titleText = "试题录入";
        this.submitButton = true;
      }
    },
    /**
     * 重置页面
     */
    reset() {
      this.form = this.originalForm; // 重置表单
      this.form.options.splice(4); // 恢复为4个
      this.$refs.ruleForm.resetFields(); // 重置校验
    },
    /**
     * 清空按钮
     */
    async formReset() {
      await this.$confirm("确定清空整个表单吗");
      this.reset();
    },
    /**
     * 返回按钮
     */
    btnCancel() {
      this.reset();
      this.$router.back();
    },
    /**
     * 新增-提交
     */
    async onSubmitAdd() {
      try {
        await this.$refs.ruleForm.validate();
        await this.$confirm("确认提交吗？");
        this.form.tags = this.form.tags.toString(); // tags转字符串
        if (this.form.questionType == 3) {
          // 简答时清空单多选数据
          this.form.options = this.originalForm.options;
        }
        await add(this.form);
        this.$message.success("提交成功");
        this.reset();
        this.$router.push("/questions/list");
      } catch (error) {
        window.console.log(error);
        window.console.log("失败");
      }
    },
    /**
     * 修改-提交
     */
    async onSubmitUpdate() {
      try {
        await this.$refs.ruleForm.validate();
        await this.$confirm("确认提交吗？");
        let form = this.form;
        let id = this.id;
        form.tags = form.tags.toString(); // tags转字符串
        if (form.questionType == 3) {
          form.options = this.originalForm.options;
        }
        window.console.log(form);
        await update({ id, ...form });
        this.$message.success("成功提交修改");
        this.reset();
        this.$router.back();
      } catch (error) {
        window.console.log(error);
        window.console.log("失败");
      }
    },
    /**
     * 修改跳转-获取数据
     */
    async getDetail() {
      if (this.id) {
        // 如果有id传过来
        let id = this.id;
        const data = await detail({ id });
        this.form = data.data;
        // 数据回填
        const right = this.form.options.map(item => item.isRight);
        this.radioCheck = right.indexOf(1); // 找出正确答案的下标赋予选项
        // 城市数据问题
        this.cityData = citys(this.form.province);
        // 目录问题
        const depts = await simpleDirectorys({
          subjectID: this.form.subjectID,
          pagesize: 10000
        });
        this.catalog = depts.data;
        // 多选问题&简答显示选项问题
        if (this.form.questionType == 3) {
          this.optionDialog = false;
        } else if (this.form.questionType == 2) {
          this.radioDialog = false;
        }
      }
    },
    // 图片 上传
    uploadIndex(index) {
      this.picIndex = index; // 上传时触发点击事件，记录上传选项的序号到pic里
    },
    /**
     * 上传成功
     */
    handleAvatarSuccess(response, file, fileList) {
      this.form.options[this.picIndex].img = response.data.url; // 按照所记录序号，将上传图片返回得到的url添加到form，随后触发v-if，显示缩略图
      this.pics[this.picIndex] = file.raw.uid; // 同时，记录下上传文件的uid，添加到pics指定序号下标里，方便删除时判断
    },
    /**
     * 移除图片
     */
    handleAvatarRemove(file, fileList) {
      let index = this.pics.indexOf(file.raw.uid); // 获取要删除的uid，从pics中找出之前记录uid的下标index
      this.form.options[index].img = ""; // 删除form中对应index下标的img
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>
<style lang="scss" scoped>
.editor {
  line-height: normal;
  height: 200px;
  margin-bottom: 40px;
}
\deep\.el-input__inner {
  box-sizing: border-box;
}
\deep\ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  // overflow: hidden;
  width: 100px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}
\deep\ .avatar-uploader .el-upload:hover {
  border: 1px dashed #0da5fa;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
}
.avatar-uploader {
  display: inline-block;
  width: 100px;
  height: 60px;
  vertical-align: middle;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.upload-text {
  display: inline-block;
  line-height: 60px;
  margin-left: 17px;
}
.question-change {
  margin-top: 25px;
}
.form-button {
  width: 520px;
  .form-reset {
    float: right;
  }
}
.option-item {
  margin-bottom: 30px;
}
.el-radio-s {
  margin-right: 0;
}
.el-icon-circle-close {
  position: absolute;
  top: 0;
  right: 0;
  margin-top: -5px;
  margin-right: -5px;
  z-index: 99999;
  background: #ffffff;
}
::v-deep .el-upload-list {
  margin-top: -20px !important;
}
</style>
